package org.fireflow2.designer.eclipse.policies;

import java.util.List;

import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.GraphicalNodeEditPolicy;
import org.eclipse.gef.requests.CreateConnectionRequest;
import org.eclipse.gef.requests.ReconnectRequest;
import org.fireflow.pdl.fpdl20.diagram.Fpdl20DiagramElement;
import org.fireflow2.designer.eclipse.commands.connection.CreateTransitionCommand;
import org.fireflow2.designer.eclipse.modelwrapper.AbsWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.ModelWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.NodeWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.SubProcessWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.EndNodeWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.StartNodeWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.TransitionWrapper;

public class NodeGraphicalNodeEditPolicy extends GraphicalNodeEditPolicy {

	protected Command getConnectionCompleteCommand(
			CreateConnectionRequest request) {
		Command commandTmp = request.getStartCommand();
		NodeWrapper targetNodeWrapper = (NodeWrapper) getHost().getModel();
		
		if (commandTmp instanceof CreateTransitionCommand) {
			CreateTransitionCommand command = (CreateTransitionCommand) commandTmp;
			NodeWrapper sourceNodeWrapper = (NodeWrapper) command.getSource();
			if (targetNodeWrapper instanceof StartNodeWrapper) {
				return null;
			}

			if (sourceNodeWrapper == targetNodeWrapper)
				return null;
			
			List<TransitionWrapper> leavingTransitions = sourceNodeWrapper.getLeavingTransitions();
			if (leavingTransitions!=null){
				for (TransitionWrapper leavingTrans : leavingTransitions){
					ModelWrapper target = leavingTrans.getTarget();
					if (target.getSn().equals(targetNodeWrapper.getSn())){
						return null;//不能连接两条transition;
					}
				}
			}
			
			command.setTarget(targetNodeWrapper);
			return command;
		}

		return null;
	}

	protected Command getConnectionCreateCommand(CreateConnectionRequest request) {
		Fpdl20DiagramElement newElementType = (Fpdl20DiagramElement) request.getNewObject();
		NodeWrapper nodeWrapper = (NodeWrapper) getHost().getModel();

		SubProcessWrapper subflowWrapper = nodeWrapper.getSubProcessWrapper();

		if (newElementType.equals(Fpdl20DiagramElement.TRANSITION)) {
			if (nodeWrapper instanceof EndNodeWrapper) {
				return null;
			} 

			CreateTransitionCommand command = new CreateTransitionCommand();
			command.setSubProcessWrapper(subflowWrapper);
			command.setSource(nodeWrapper);
			request.setStartCommand(command);
			
			return command;
		} 
		
		return null;
	}

	protected Command getReconnectSourceCommand(ReconnectRequest request) {
		return null;
	}

	protected Command getReconnectTargetCommand(ReconnectRequest request) {
		return null;
	}

}
